import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/reports.dart';
import 'package:ichinesereader/exam/widgets/SampleAudioPlayer.dart';
import 'package:ichinesereader/models/report/basketsResult.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/buttons/debouncedMaterialButton.dart';
import 'package:reactive_forms/reactive_forms.dart';

class BasketGrade extends StatefulWidget {
  BasketGrade({Key? key, required this.basketItem}) : super(key: key);
  final BasketItem basketItem;
  _BasketGrade createState() => new _BasketGrade();
}

class _BasketGrade extends State<BasketGrade> {
  ReportsController _reportsController = Get.find();
  bool _isGradeMode = true;
  final box = Hive.box('appconfig');
  var _textEditingController = TextEditingController();
  String _recordingFile = '';
  bool isTeacher = false;

  final form = FormGroup({
    'grade': FormControl<String>(validators: [Validators.required]),
    'comment': FormControl<String>(),
  });

  @override
  void initState() {
    isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;
    var basketItem = widget.basketItem;
    _textEditingController.text = basketItem.content?.text ?? '';
    var isGradeMode = basketItem.status?.toUpperCase() != "GRADED";
    form.control('grade').value =
        isGradeMode ? null : basketItem.content!.grade;
    form.control('comment').value =
        isGradeMode ? null : basketItem.content!.comment;

    if (basketItem.status == "NEW") {
      _reportsController.basketReview(
          basketItem.contentType!.toLowerCase(),
          basketItem.player!.userName!,
          basketItem.bookId!,
          basketItem.assignmentId,
          basketItem.id);
    }
    setState(() {
      _isGradeMode = isGradeMode;
    });
    if (basketItem.contentType == "RECORDING") {
      _reportsController
          .fetchRecordingFile(basketItem.content!.location!)
          .then((file) {
        setState(() {
          _recordingFile = file;
        });
      });
    }
    super.initState();
  }

  void _onSubmit() {
    if (_isGradeMode) {
      if (!form.valid) {
        form.markAllAsTouched();
        return;
      } else {
        var basketItem = widget.basketItem;
        _reportsController.basketGrade(
            basketItem.contentType!.toLowerCase(),
            basketItem.player!.userName!,
            basketItem.bookId!,
            basketItem.assignmentId,
            form.control('grade').value,
            form.control('comment').value,
            basketItem.id);
      }
    }
    Future.delayed(Duration(milliseconds: 1200), (() {
      Navigator.of(context).pop();
    }));
  }

  @override
  Widget build(BuildContext context) {
    var basketItem = widget.basketItem;
    Log.debug('Build basket grade page');
    return AlertDialog(
      title: isTeacher
          ? Text(
              '${basketItem.player?.userName!} ${basketItem.contentType?.toLowerCase()}')
          : Text(''),
      titleTextStyle: TextStyle(
          fontWeight: FontWeight.bold,
          letterSpacing: 1,
          color: Get.isDarkMode ? Color(0xffcccccc) : Colors.black,
          fontSize: 20),
      backgroundColor: Get.isDarkMode
          ? (Color(0xff333333))
          : Color.fromARGB(255, 234, 241, 238),
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(20))),
      content: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        child: Container(
          height: 520,
          width: MediaQuery.of(context).size.width * 0.80,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  basketItem.contentType == "RECORDING"
                      ? Container(
                          height: 280,
                          width: MediaQuery.of(context).size.width * 0.75,
                          //alignment: Alignment.center,
                          child: Column(children: [
                            Image.network(basketItem.bookImageUrl!),
                            Visibility(
                                visible: _recordingFile.startsWith('https'),
                                child: SampleAudioPlayer(
                                    name: 'recording',
                                    audioUrl: _recordingFile)),
                          ]),
                        )
                      : basketItem.contentType == "WRITING"
                          ? Container(
                              height: 280,
                              width: MediaQuery.of(context).size.width * 0.75,
                              child: TextField(
                                controller: _textEditingController,
                                maxLines: 25,
                                maxLength: 2500,
                                decoration: InputDecoration(
                                  border: OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(8.0)),
                                ),
                              ),
                              decoration: BoxDecoration(
                                  color: Color.fromARGB(50, 167, 169, 170),
                                  borderRadius: BorderRadius.circular(12)))
                          : Text("")
                ],
              ),
              ReactiveForm(
                formGroup: form,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    Container(
                        padding: EdgeInsets.all(15),
                        decoration: BoxDecoration(
                          border: Border.all(
                            color: const Color(0xff7c94b6),
                            width: 0.5,
                          ),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Column(
                          children: [
                            ReactiveTextField(
                              readOnly: !_isGradeMode,
                              formControlName: 'grade',
                              textInputAction: TextInputAction.next,
                              style: Theme.of(context).textTheme.titleSmall,
                              onSubmitted: (_) => form.focus('grade'),
                              decoration: InputDecoration(
                                labelText: 'Score'.tr,
                              ),
                            ),
                            SizedBox(
                              height: 12,
                            ),
                            ReactiveTextField(
                              readOnly: !_isGradeMode,
                              formControlName: 'comment',
                              textInputAction: TextInputAction.next,
                              style: Theme.of(context).textTheme.titleSmall,
                              onSubmitted: (_) => form.focus('comment'),
                              decoration: InputDecoration(
                                labelText: 'Comment'.tr,
                              ),
                            ),
                          ],
                        )),
                    SizedBox(
                      height: 12,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        MaterialButton(
                            color: Get.isDarkMode
                                ? (Color(0xff444444))
                                : (Colors.white),
                            textColor: Get.isDarkMode
                                ? (Color(0xffcccccc))
                                : Theme.of(context).primaryColorDark,
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                            child: Text('Close'.tr)),
                        SizedBox(
                          width: 20,
                        ),
                        _isGradeMode && isTeacher
                            ? ReactiveFormConsumer(
                                builder: (context, form, child) {
                                  return DebouncedMaterialButton(
                                      debounceTimeMs: 1800,
                                      color: Get.isDarkMode
                                          ? (Colors.white)
                                          : Theme.of(context).primaryColorDark,
                                      textColor: Get.isDarkMode
                                          ? (Colors.black)
                                          : Theme.of(context).primaryColorLight,
                                      onPressed: _onSubmit,
                                      child: Text('Submit'.tr));
                                },
                              )
                            : Text("")
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
